// 定义Promise的三种状态
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';

class MyPromise {
    // 构造函数，接收一个执行器函数
    constructor(executor) {
        // 初始状态为pending
        this.status = PENDING;
        // 成功的值，初始为undefined
        this.value = undefined;
        // 失败的原因，初始为undefined
        this.reason = undefined;
        // 存储成功的回调函数
        this.onFulfilledCallbacks = [];
        // 存储失败的回调函数
        this.onRejectedCallbacks = [];

        // 定义resolve函数
        const resolve = (value) => {
            // 只有状态为pending时才能进行状态转换
            if (this.status === PENDING) {
                // 将状态转换为fulfilled
                this.status = FULFILLED;
                // 保存成功的值
                this.value = value;
                // 执行所有成功的回调函数
                this.onFulfilledCallbacks.forEach((callback) => callback());
            }
        };

        // 定义reject函数
        const reject = (reason) => {
            // 只有状态为pending时才能进行状态转换
            if (this.status === PENDING) {
                // 将状态转换为rejected
                this.status = REJECTED;
                // 保存失败的原因
                this.reason = reason;
                // 执行所有失败的回调函数
                this.onRejectedCallbacks.forEach((callback) => callback());
            }
        };

        try {
            // 执行执行器函数，传入resolve和reject函数
            executor(resolve, reject);
        } catch (error) {
            // 如果执行器函数抛出错误，调用reject函数
            reject(error);
        }
    }

    // then方法，用于处理Promise的结果
    then(onFulfilled, onRejected) {
        // 如果onFulfilled不是函数，将其转换为一个返回值的函数
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;
        // 如果onRejected不是函数，将其转换为一个抛出错误的函数
        onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason; };

        // 创建一个新的Promise对象
        const newPromise = new MyPromise((resolve, reject) => {
            // 定义处理成功结果的函数
            const handleFulfilled = () => {
                try {
                    // 执行成功的回调函数
                    const result = onFulfilled(this.value);
                    // 处理回调函数的返回值
                    resolvePromise(newPromise, result, resolve, reject);
                } catch (error) {
                    // 如果回调函数抛出错误，调用reject函数
                    reject(error);
                }
            };

            // 定义处理失败结果的函数
            const handleRejected = () => {
                try {
                    // 执行失败的回调函数
                    const result = onRejected(this.reason);
                    // 处理回调函数的返回值
                    resolvePromise(newPromise, result, resolve, reject);
                } catch (error) {
                    // 如果回调函数抛出错误，调用reject函数
                    reject(error);
                }
            };

            // 根据Promise的状态进行不同的处理
            if (this.status === FULFILLED) {
                // 如果状态为fulfilled，立即执行处理成功结果的函数
                setTimeout(handleFulfilled, 0);
            } else if (this.status === REJECTED) {
                // 如果状态为rejected，立即执行处理失败结果的函数
                setTimeout(handleRejected, 0);
            } else {
                // 如果状态为pending，将处理成功和失败结果的函数存储起来
                this.onFulfilledCallbacks.push(() => setTimeout(handleFulfilled, 0));
                this.onRejectedCallbacks.push(() => setTimeout(handleRejected, 0));
            }
        });

        return newPromise;
    }

    // catch方法，用于处理Promise的失败结果
    catch(onRejected) {
        return this.then(null, onRejected);
    }

    // finally方法，无论Promise状态如何都会执行
    finally(callback) {
        return this.then(
            (value) => MyPromise.resolve(callback()).then(() => value),
            (reason) => MyPromise.resolve(callback()).then(() => { throw reason; })
        );
    }

    // 静态方法resolve，用于创建一个已解决的Promise
    static resolve(value) {
        if (value instanceof MyPromise) {
            return value;
        }
        return new MyPromise((resolve) => resolve(value));
    }

    // 静态方法reject，用于创建一个已拒绝的Promise
    static reject(reason) {
        return new MyPromise((_, reject) => reject(reason));
    }

    // 静态方法all，用于并行处理多个Promise
    static all(promises) {
        return new MyPromise((resolve, reject) => {
            const results = [];
            let completedCount = 0;

            const processPromise = (index, promise) => {
                promise.then(
                    (value) => {
                        results[index] = value;
                        completedCount++;
                        if (completedCount === promises.length) {
                            resolve(results);
                        }
                    },
                    (reason) => {
                        reject(reason);
                    }
                );
            };

            for (let i = 0; i < promises.length; i++) {
                processPromise(i, promises[i]);
            }
        });
    }

    // 静态方法race，用于并行处理多个Promise，哪个先完成就返回哪个的结果
    static race(promises) {
        return new MyPromise((resolve, reject) => {
            for (let i = 0; i < promises.length; i++) {
                promises[i].then(
                    (value) => {
                        resolve(value);
                    },
                    (reason) => {
                        reject(reason);
                    }
                );
            }
        });
    }
}

// 辅助函数，用于处理then方法中回调函数的返回值
function resolvePromise(newPromise, result, resolve, reject) {
    if (newPromise === result) {
        return reject(new TypeError('Chaining cycle detected for promise'));
    }
    if (result instanceof MyPromise) {
        result.then(resolve, reject);
    } else {
        resolve(result);
    }
}

module.exports = MyPromise;